from info.auth import auth_bp
from flask import render_template, request, redirect
from model import *
from flask_restful.reqparse import RequestParser
from flask_login import login_user


@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        parser = RequestParser()
        parser.add_argument('password')
        parser.add_argument('username')
        res = parser.parse_args()
        user = User.query.filter_by(username=res.username, password=res.password).first()
        if user:
            login_user(user)
            return redirect('/admin')
        else:
            return render_template('auth/登录-弹窗.html')

    return render_template('auth/登录.html')


@auth_bp.route('/register', methods=['POST', 'GET'])
def register():
    if request.method == 'POST':
        parser = RequestParser()
        parser.add_argument('username', location='form')
        parser.add_argument('password', location='form')
        parser.add_argument('city', location='form')
        parser.add_argument('hobby', action='append', location='form')
        parser.add_argument('sex', location='form')
        parser.add_argument('text', location='form')
        res = parser.parse_args()
        user_data = {
            'username': res.username,
            'password': res.password,
            'city': res.city,
            'hobby': ','.join(res.hobby),
            'sex': res.sex,
            'text': res.text
        }
        user = User(**user_data)
        db.session.add(user)
        db.session.commit()
        return redirect(f'/auth/login')
    return render_template('auth/注册.html')
